package com.xsomnus.rpc.common.codec;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/22 0022 13:50
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 *  <pre>
 *      基于fastjson的编码器
 *  </pre>
 */
public class FastJsonEncoder extends MessageToMessageEncoder {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, List out) throws Exception {
        byte[] bytes = JSON.toJSONBytes(msg);
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer();
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
        out.add(byteBuf);
    }
}
